package app.keter.portal.security.core;

import app.keter.portal.config.Services;
import com.keter.framework.web.result.JSONResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

/**
 * Created by gkatzioura on 10/5/16.
 */
@Primary
@Component
public class PasswordEncoderImpl implements PasswordEncoder {

    private static final Logger logger = LoggerFactory.getLogger(PasswordEncoderImpl.class);

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    Services services;

    private String ENCODE_API;

    @Autowired void init() {
        ENCODE_API = services.getCommon() + "/api/v1/security/encoder";
    }

    @Override
    public String encode(CharSequence rawPassword) {
          return restTemplate.getForObject(
                ENCODE_API+"/{1}", JSONResult.class,rawPassword).data();
    }

    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {
        String result =  restTemplate.getForObject(ENCODE_API + "?rawPassword={1}&encodedPassword={2}",
                JSONResult.class,rawPassword,encodedPassword).data();
        return Boolean.valueOf(result);
    }

}
